package com.mh.zookeeper.api;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.List;

import static com.mh.zookeeper.PropertiesUtils.getZookeeperConnectStr;

/**
 * @author MH
 * @since 2021-12-21
 */
public class GetNodeData implements Watcher {

    private static ZooKeeper zooKeeper;

    public static void main(String[] args) throws IOException, InterruptedException {

        zooKeeper = new ZooKeeper(getZookeeperConnectStr(), 5000, new GetNodeData());
        System.out.println(zooKeeper.getState());

        Thread.sleep(Integer.MAX_VALUE);

    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {

            List<String> children = null;
            try {
                children = zooKeeper.getChildren("/lg-persistent", true);
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(children);
        }

        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {

            try {
                getNoteData();
                getChildren();
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }


        }


    }

    private void getNoteData() throws KeeperException, InterruptedException {
        byte[] data = zooKeeper.getData("/lg-persistent", false, null);
        System.out.println(new String(data));
    }

    public static void getChildren() throws KeeperException, InterruptedException {

        List<String> children = zooKeeper.getChildren("/lg-persistent", true);
        System.out.println(children);


    }
}